<template>
  <div class="">
    <a-spin :loading="spinLoading" :tip="spinTip" dot style="width: 100%;">
      <a-card class="custom-card">
        <div ref="searchRef">
          <a-row class="table-search mb-3">
            <a-col :flex="1">
              <a-form
                :model="query"
                layout="inline"
                label-align="left"
              >
                <a-row :gutter="16">
                  <a-col flex="300px">
                    <a-range-picker v-model="query.range_date" allow-clear/>
                  </a-col>
                  <a-col :flex="'86px'">
                    <a-space :size="6">
                      <a-button type="primary" @click="search">
                        <template #icon><icon-search /></template>搜索
                      </a-button>
                      <a-button @click="refresh()">
                        <template #icon><icon-refresh /></template>重置
                      </a-button>
                    </a-space>
                  </a-col>
                </a-row>
              </a-form>
            </a-col>
          </a-row>
        </div>
        <div class="table-header lg:flex justify-between mb-2">

        </div>
        <div ref="tableContainerRef">
          <Chart v-if="xAxis.length" style="height: 400px; margin-top: 20px" :option="chartOption" />
        </div>
      </a-card>
    </a-spin>
  </div>
</template>

<script setup>
  import { ref, reactive, h, compile, nextTick, onMounted, onUnmounted } from 'vue';
  import dayjs from 'dayjs';

  import useLoading from '@/hooks/loading';
  import { workAreaHeight } from '@/utils/index';
  import useChartOption from '@/hooks/chart-option';
  import { apiChart } from '@/api/member';

  const { loading, setLoading } = useLoading(true);
  const baseQuery = () => {
    return {
      range_date: [],
    };
  };
  const query = ref(baseQuery());

  const searchRef = ref();
  const showSearch = ref(true);
  const tableContainerRef = ref();
  const searchHeight = ref(0);

  const spinLoading = ref(false);
  const spinTip = ref();

  const settingFixedPage = () => {
    const workHeight = workAreaHeight();
    const tableHeight = workHeight - searchHeight.value;
    tableContainerRef.value.style.height = `${tableHeight}px`;
  };
  const resizeHandler = () => {
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  };

  // 提示框浮层内容格式器
  const tooltipItemsHtmlString = (items) => {
    return items.map(
      (el) => `<div class="content-panel">
        <p>
          <span style="background-color: ${el.color}" class="tooltip-item-icon"></span><span>${el.seriesName}</span>
          <span class="tooltip-value">${el.value}</span>
        </p>
      </div>`
    ).reverse().join('');
  };
  // 图表配置
  const generateSeries = (
    name,
    itemColor,
    itemBorderColor,
    data,
    seriesType,
    yAxisIndex,
    smooth,
    lineStyleType,
  ) => {
    const option = {
      name,
      data,
      // stack: 'Total',
      type: seriesType,
      // yAxisIndex, // 使用的 y 轴的 index，在单个图表实例中存在多个 y轴的时候有用
      smooth, // 是否平滑曲线显示
      symbol: 'circle', // 标记的图形
      symbolSize: 6, // 标记的大小
      showSymbol: true, // 是否显示 symbol, 如果 false 则只有在 tooltip hover 的时候显示
      // 折线拐点标志的样式
      itemStyle: {
        color: itemColor,
      },
      // 折线图的高亮状态
      emphasis: {
        focus: 'series',
        itemStyle: {
          color: itemColor,
          borderWidth: 2,
          borderColor: itemBorderColor,
        },
      },
      // 线条样式
      lineStyle: {
        width: 2,
        type: lineStyleType, // solid：实线，dotted：点型虚线，dashed：线性虚线
        color: itemColor,
      },
      // 区域填充样式。设置后显示成区域面积图
      areaStyle: {
        opacity: 0.1,
        color: itemColor,
      },
    };
    if (yAxisIndex) {
      option.yAxisIndex = yAxisIndex;
    }
    return option;
  };
  const xAxis = ref([]); // 天
  const countDatas = ref([]);
  const count2Datas = ref([]);
  const count3Datas = ref([]);
  const chartOption = ref();

  const reset = async () => {
    xAxis.value = [];
    countDatas.value = [];
    count2Datas.value = [];
    count3Datas.value = [];
  };
  // 列表
  const fetchData = async () => {
    setLoading(true);
    await reset();
    try {
      query.value.range_date = [
        dayjs().subtract(15, 'day').format('YYYY-MM-DD'),
        dayjs().format('YYYY-MM-DD'),
      ];
      await search();
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };
  // 分析
  const search = async () => {
    setLoading(true);
    try {
      const { data } = await apiChart(query.value);
      xAxis.value = data.member.days;
      countDatas.value = data.member.actives;
      count2Datas.value = data.member.news;
      count3Datas.value = data.member.totals;

      const chartOptionData = useChartOption((dark) => {
        let chartSelected = {
          '会员数': true,
          '文章数': true,
        };
        let chartSeries = [
          generateSeries(
            '会员数',
            '#F53F3F',
            '#F53F3F',
            countDatas.value,
            'bar',
            0,
            true,
            'solid',
          ),
          generateSeries(
            '文章数',
            '#12A134',
            '#12A134',
            count2Datas.value,
            'bar',
            0,
            true,
            'solid',
          ),
        ];

        chartSelected['点击量'] = true;
        chartSeries.push(generateSeries(
          '点击量',
          '#FFB400',
          '#FFB400',
            count3Datas.value,
          'line',
          1,
          true,
          'solid',
        ));

        return {
          // 直角坐标系内绘图网格
          grid: {
            left: '6%',
            right: '6%',
            top: '80',
            bottom: '100',
          },
          // 图例组件展现了不同系列的标记(symbol)，颜色和名字。可以通过点击图例控制哪些系列不显示。
          legend: {
            icon: 'circle',
            textStyle: {
              color: '#4E5969',
            },
            selected: chartSelected,
          },
          // 直角坐标系 grid 中的 x 轴
          xAxis: {
            type: 'category',
            offset: 4,
            data: xAxis.value,
            boundaryGap: true, // 坐标轴两边留白策略
            // 坐标轴刻度标签的相关设置
            axisLabel: {
              interval: 0, // 坐标轴刻度标签的显示间隔，设置成 0 强制显示所有标签
              rotate: 30, // 旋转的角度从 -90 度到 90 度
              color: '#4E5969',
              // 刻度标签的内容格式器【使用函数模板，函数参数分别为刻度数值（类目），刻度的索引】
              formatter(value, idx) {
                return `${value}`;
              },
            },
            axisLine: {
              show: true, // 是否显示坐标轴轴线
            },
            axisTick: {
              show: true, // 是否显示坐标轴刻度
            },
            splitLine: {
              show: false, // 是否显示分隔线。默认数值轴显示，类目轴不显示
            },
            // 坐标轴指示器配置项
            axisPointer: {
              show: true,
              lineStyle: {
                color: '#23ADFF',
                width: 2,
              },
            },
          },
          // 直角坐标系 grid 中的 y 轴
          yAxis: [
            {
              type: 'value',
              name: '数量', // 坐标轴名称
              // splitNumber: 5, // 坐标轴的分割段数
              // interval: '',
              axisLine: {
                show: true, // 是否显示坐标轴轴线
              },
              // 坐标轴刻度标签的相关设置
              axisLabel: {
                formatter(value, idx) {
                  if (idx === 0) {
                    return String(value);
                  }
                  // return `${value / 1000}k`;
                  return `${value}`;
                },
              },
              // 坐标轴在 grid 区域中的分隔线
              splitLine: {
                lineStyle: {
                  color: dark ? '#2E2E30' : '#F2F3F5',
                },
              },
            },
            {
              type: 'value',
              name: '比率',
              axisLine: {
                show: false,
              },
              axisLabel: {
                formatter(value, idx) {
                  return `${value}%`;
                },
              },
            },
          ],
          // 提示框组件
          tooltip: {
            trigger: 'axis',
            // 提示框浮层内容格式器
            formatter(params) {
              const [firstElement] = params;
              return `<div>
                <p class="tooltip-title">${firstElement.axisValueLabel}</p>
                ${tooltipItemsHtmlString(params)}
              </div>`;
            },
            className: 'echarts-tooltip-diy',
          },
          // 图表
          series: chartSeries,
        };
      });
      chartOption.value = chartOptionData.chartOption.value;
    } catch (err) {
      // you can report use errorHandler or other
    } finally {
      setLoading(false);
    }
  };

  onMounted(async () => {
    await fetchData();
    window.addEventListener('resize', resizeHandler, false);
    searchHeight.value = searchRef.value.offsetHeight;
    settingFixedPage();
  });
  onUnmounted(() => {
    window.removeEventListener('resize', resizeHandler, false);
  });
</script>

<script>
  export default {
    name: 'MemberChart',
  };
</script>

<style scoped lang="less">

</style>
